package com.ticket.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ticket.entity.User;
import com.ticket.config.JwtConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
public class JwtUtils {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

    public String generateToken(User user) {
        return JWT.create()
                .withSubject(user.getUsername())
                .withClaim("userId", user.getId())
                .withClaim("role", user.getRole())
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + expiration))
                .sign(Algorithm.HMAC256(secret));
    }

    private String extractToken(String bearerToken) {
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return bearerToken;
    }

    public DecodedJWT getDecodedToken(String bearerToken) {
        String token = extractToken(bearerToken);
        return JWT.require(Algorithm.HMAC256(secret))
                .build()
                .verify(token);
    }

    public boolean validateToken(String bearerToken) {
        try {
            getDecodedToken(bearerToken);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public Long getUserIdFromToken(String bearerToken) {
        return getDecodedToken(bearerToken).getClaim("userId").asLong();
    }

    public String getUsernameFromToken(String bearerToken) {
        return getDecodedToken(bearerToken).getSubject();
    }

    public String getRoleFromToken(String bearerToken) {
        return getDecodedToken(bearerToken).getClaim("role").asString();
    }

}
